<?php

namespace addons\cloud_market\controller\api;

use addons\cloud_market\model\CloudMarketOrder;
use addons\cloud_market\model\CloudMarketSite;
use addons\cloud_market\model\CloudMarketUser;
use addons\cloud_market\utils\Sms as SmsUtils;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Validate;

class User extends CloudMarketApiController
{
    protected $notApiLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'];
    protected $notApiCheck = ['*'];

    /**
     * @var CloudMarketUser
     */
    protected $model;

    /**
     * 当前登录用户
     * @var CloudMarketUser
     */
    protected $user = null;

    /**
     * 当前用户Token
     * @var string
     */
    protected $token = '';

    /**
     * Token默认有效时长
     * @var int
     */
    protected $keeptime = 2592000;

    /**
     * 允许输出的字段
     * @var array
     */
    protected $allowFields = ['id', 'username', 'nickname', 'mobile', 'avatar', 'money', 'score', 'email','developer','topuid','uid'];

    public function initialize()
    {

        parent::initialize();
        $this->model = new CloudMarketUser();
    }


    /**
     * 会员中心
     */
    public function index()
    {
        $getCount = input('getCount', false);

        return $this->success("", $this->getUserAllData($getCount));
    }

    public function sites()
    {
        $search = input('search', '');
        $user = $this->getUser();
        $where = array();
        if ($search) {
            $where[] = ['title|domain', 'like', '%' . $search . '%'];
        }
        $res = CloudMarketSite::where(['user_id' => $user['id']])
            ->where($where)
            ->order('update_time', 'desc')
            ->limit(0, 10)
            ->select();
        if (count($res)) {
            foreach ($res as $key => $value) {
                $res[$key]['label'] = $value['title'] . '  [ ' . $value['domain'] . ' ]';
            }
        } else {
            $res = array();
        }
        return $this->success('', $res);
    }


    /**
     * 会员登录
     *
     * @param string $account 账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        // 这里登录采用官方登录方式
        if ($this->auth->login($account, $password) && !$this->auth->getError()) {
            // 系统本身用户
            $systemUserinfo = $this->auth->getUserinfo();
            $user = (new CloudMarketUser())->where(['uid' => $systemUserinfo['uid']])->find();
            $ip = $this->request->ip();
            // 记录本次登录的IP和时间
            $user->loginip = $ip;
            $user->save();
            $this->userInfo = $user;
            $this->token = $this->auth->getToken();
            return $this->success("登录成功", $this->getUserAllData());
        } else {
            // 账号不存在
            // 创建账号
            return $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function mobileLogin()
    {
        $mobile = $this->request->post('mobile');
        $event = 'login_register';
        $captcha = $this->request->post('captcha');
        if (!$mobile || !Validate::regex($mobile, "^1\d{10}$")) {
            return $this->error('手机号不正确');
        }
        $user = CloudMarketUser::where('mobile', $mobile)->find();
        $ret = SmsUtils::check($mobile, $captcha, $event);
//        $ret = true;
        if ($ret) {
            if (!$user) {
                // 注册一个账号
                $ip = request()->ip();
                $time = time();
                $data = [
                    'phone'  => $mobile,
                    'avatar' => '',
                ];
                $params = array_merge($data, [
                    'join_ip'    => $ip,
                    'login_time' => $time,
                    'login_ip'   => $ip,
                    'status'     => 0
                ]);
                // 启动事务
                Db::startTrans();
                try {
                    // 注册系统账号
                    $systemUser = \app\common\model\user\User::create($params);

                    // 注册用户账号
                    $this->userInfo = CloudMarketUser::create([
                        'uid'     => $systemUser['uid'],
                        'mobile'  => $mobile,
                        'joinip'  => $ip,
                        'loginip' => $ip,
                    ]);
                    //直接登录会员
                    $this->auth->direct($systemUser->uid);
                    $this->token = $this->auth->getToken();
                    // 提交事务
                    Db::commit();
                    return $this->success('注册成功', $this->getUserAllData());
                } catch (\Exception $e) {
                    // 回滚事务
                    $this->setError($e->getMessage());
                    Db::rollback();
                    return $this->error('注册失败', $e->getMessage());
                }

            } else {
                $this->auth->direct($user->uid);
                $ip = $this->request->ip();
                // 记录本次登录的IP和时间
                $user->loginip = $ip;
                $user->save();
                $this->userInfo = $user;
                $this->token = $this->auth->getToken();
                return $this->success('成功', $this->getUserAllData());
            }
        } else {
            return $this->error('验证码不正确');
        }
    }

    /**
     * 个人信息修改
     * Create by :  刘泓宾<514660094@qq.com>
     * @return \think\response\Json
     */
    public function profile()
    {
        $user = $this->userInfo;
        $avatar = input('avatar', []);
        $nickname = input('nickname', '');
        $email = input('email', '');
        $username = input('username', '');
        $password = input('password', '');
        $data = array();
        if (count($avatar)) {
            $data['avatar'] = $avatar[0];
        }
        if(!$nickname  && $username){
            $nickname = $username;
        }
        if ($nickname) {
            $res = (new CloudMarketUser())->where(['nickname' => $nickname])->find();
            if ($res) {
                if ($res['id'] == $user['id']) {
                    return $this->success('未修改内容');
                }
                if ($res['id'] != $user['id']) {
                    return $this->error('昵称已存在');
                }
            }
            $data['nickname'] = $nickname;
        }
        if ($email) {
            $res = (new CloudMarketUser())->where(['email' => $email])->find();
            if ($res) {
                if ($res['id'] == $user['id']) {
                    return $this->success('未修改内容');
                }
                if ($res['id'] != $user['id']) {
                    return $this->error('邮箱已存在');
                }
            }
            $data['email'] = $email;
        }

        if ($username) {
            if ($user['username']) {
                return $this->error('禁止修改用户名');
            }
            $data['username'] = $username;
            // 这里要同步到系统用户表
            $systemUser = (new \app\common\model\user\User())->find($user->uid);
            $systemUser->username = $username;
            $systemUser->save();
        }
        if($password) {
            // 修改密码
           $this->auth->changePwdByUid($user->uid, $password);
        }

        $user->avatar = $avatar;
        $user->save($data);
        return $this->success('修改成功', $avatar);
    }


    /**
     * 修改手机号
     *
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
//    public function changemobile()
//    {
//        $this->checkLogin();
//
//        $mobile = $this->request->request('mobile');
//        $captcha = $this->request->request('captcha');
//
//        if (!$mobile || !$captcha) {
//            return $this->error('参数错误');
//        }
//
//        if (!Validate::regex($mobile, "^1\d{10}$")) {
//            return $this->error('手机号格式错误');
//        }
//
//        if ($this->model->where('mobile', $mobile)->where('id', '<>', $this->userInfo->id)->find()) {
//            return $this->error('手机号已存在');
//        }
//
//        if (!$this->checkCaptcha($mobile, $captcha, 'changemobile')) {
//            return $this->error('验证码错误');
//        }
//
//        $this->userInfo->mobile = $mobile;
//        $this->userInfo->save();
//
//        $this->flushCaptcha($mobile, 'changemobile');
//        return $this->success('修改成功');
//    }

    /**
     * 重置密码
     *
     * @param string $mobile 手机号
     * @param string $newpassword 新密码
     * @param string $captcha 验证码
     */
    public function resetpwd()
    {
        $mobile = $this->request->post('mobile');
        $password = $this->request->post('password');
        $captcha = $this->request->post('captcha');
        if (!$password || !$captcha) {
            return $this->error('参数错误');
        }

        if (!Validate::regex($mobile, "^1\d{10}$")) {
            return $this->error('手机号格式错误');
        }
        // 这里获取的是当前系统的的手机号
        $user = $this->model->where('mobile', $mobile)->find();
        if (!$user) {
            return $this->error('用户不存在');
        }
//        if (!SmsUtils::check($mobile, $captcha,'resetpwd')) {
//            return $this->error('验证码错误');
//        }
        // 模拟登录
//        $this->directLogin($user->id);
//        $ret = $this->changepwd($newpassword, '', true);
        $this->auth->direct($user->uid);
        // 系统用户
//        $systemUser = $this->auth->getUserinfo();
        // 云端用户
        $this->userInfo = $user;
        // 修改密码
        $ret = $this->auth->changePwdByUid($user->uid, $password);
        if ($ret) {
            return $this->success('重置密码成功',$this->getUserAllData());
        } else {
            return $this->error($this->getError());
        }
    }

    /**
     * 修改密码
     *
     * @param string $newpassword 新密码
     * @param string $oldpassword 旧密码
     * @param bool $ignoreoldpassword 忽略旧密码
     * @return bool
     */
//    public function changepwd($newpassword, $oldpassword = '', $ignoreoldpassword = false)
//    {
//        if (!$this->userInfo) {
//            $this->setError('请先登录');
//            return false;
//        }
//
//        // 判断旧密码是否正确
//        if ($this->userInfo->password == $this->getEncryptPassword($oldpassword, $this->userInfo->salt) || $ignoreoldpassword) {
//            Db::startTrans();
//            try {
//                $salt = Random::alnum();
//                $newpassword = $this->getEncryptPassword($newpassword, $salt);
//                $this->userInfo->save(['password' => $newpassword, 'salt' => $salt]);
//
//                // 清除所有Token
//                CloudMarketToken::clear($this->userInfo->id);
//
//                // 修改密码成功的事件
//                Event::trigger('user_changepwd_successed', $this->userInfo);
//                Db::commit();
//            } catch (Exception $e) {
//                Db::rollback();
//                $this->setError($e->getMessage());
//                return false;
//            }
//            return true;
//        } else {
//            $this->setError('原密码错误');
//            return false;
//        }
//    }


    /**
     * 获取会员基本信息
     */
    protected function getUserinfo()
    {
        if (!$this->userInfo) {
            return [];
        }
        $data = $this->userInfo->toArray();
//        $data['avatar'] = $data['avatar'] ? cdnurl($data['avatar']) : '';
        // 获取开发者信息
        $allowFields = $this->getAllowFields();
        $userinfo = array_intersect_key($data, array_flip($allowFields));
        return $userinfo;
    }

    /**
     * 获取用户所有数据
     * @return array
     */
    protected function getUserAllData($getCount = false)
    {
        $userinfo = $this->getUserinfo();
        $data = [
            'userinfo' => $userinfo,
            'token'    => $this->auth->getToken(),
            'roles'    => []
        ];
        // 获取数据
        if ($getCount) {
            $data['counts'] = array(
                'site'  => (new CloudMarketSite())->where(['user_id' => $userinfo['id']])->count(),
                'order' => (new CloudMarketOrder())->where(['user_id' => $userinfo['id']])->count(),
                //                'token' => (new CloudMarketSiteAddonToken())->where(['user_id' => $userinfo['id']])->count()
            );
        }
        return $data;
    }

    /**
     * 获取允许输出的字段
     *
     * @return array
     */
    protected function getAllowFields()
    {
        return $this->allowFields;
    }

    /**
     * 设置允许输出的字段
     *
     * @param array $fields
     */
    protected function setAllowFields($fields)
    {
        $this->allowFields = $fields;
    }

    /**
     * 获取密码加密后的字符串
     *
     * @param string $password 密码
     * @param string $salt 密码盐
     * @return string
     */
    protected function getEncryptPassword($password, $salt = '')
    {
        return md5(md5($password) . $salt);
    }

    /**
     * 检查验证码
     *
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     * @param string $event 事件类型
     * @return bool
     */
    protected function checkCaptcha($mobile, $captcha, $event)
    {
        $key = "captcha_{$event}_{$mobile}";
        $data = Cache::get($key);

        if (!$data) {
            return false;
        }

        return $data['code'] === $captcha && $data['expire'] > time();
    }

    /**
     * 清除验证码
     *
     * @param string $mobile 手机号
     * @param string $event 事件类型
     * @return bool
     */
    protected function flushCaptcha($mobile, $event)
    {
        $key = "captcha_{$event}_{$mobile}";
        return Cache::delete($key);
    }

    /**
     * 设置验证码
     *
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     * @param string $event 事件类型
     * @param int $expire 过期时间(秒)
     * @return bool
     */
    protected function setCaptcha($mobile, $captcha, $event, $expire = 300)
    {
        $key = "captcha_{$event}_{$mobile}";
        $data = [
            'code'   => $captcha,
            'expire' => time() + $expire
        ];
        return Cache::set($key, $data, $expire);
    }

    /**
     * 错误信息
     * @var string
     */
    protected $error = '';

    /**
     * 设置错误信息
     *
     * @param string $error 错误信息
     * @return $this
     */
    protected function setError($error)
    {
        $this->error = $error;
        return $this;
    }

    /**
     * 获取错误信息
     *
     * @return string
     */
    protected function getError()
    {
        return $this->error ?: '';
    }
}
